package com.relsell.admin;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.relsell.pointofsales.R;
import com.relsell.utility.AppVars;
import com.relsell.utility.UserViewData;

/**
 * ChangeRoles class changes roles for a user among manager, normal user and
 * admin.<br>
 * It provides User Interface to Admin.
 * 
 */
public class ChangeRoles extends Fragment implements OnClickListener {
	
	public int userCount;
	public ArrayList<UserViewData> viewDataList = new ArrayList<UserViewData>();
	public ArrayList<UserViewData> dataSendList = new ArrayList<UserViewData>();
	

	public ChangeRoles() {

	}

	TextView user, tv1, tv2, tv3;
	Button edit, change;
	EditText user1, user2, user3;
	private ListView lst;
	private Button getAllValue;
	private EditorAdapter adapter;
	

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.changeroles, container, false);
		user = (TextView) v.findViewById(R.id.tvUser);
		String data = this.getActivity().getIntent().getExtras()
				.getString("username");
		user.setText(data);
		edit = (Button) v.findViewById(R.id.btnEdit);
		change = (Button) v.findViewById(R.id.btnChange);
		lst = (ListView) v.findViewById(R.id.lst);
		populatearraylist();
		adapter = new EditorAdapter(getActivity(), viewDataList,dataSendList);
		lst.setAdapter(adapter);
		
		
		change.setVisibility(View.INVISIBLE);
		edit.setOnClickListener(this);
		change.setOnClickListener(this);
		return v;
	}

	private void populatearraylist() {
		UserViewData row = null;
		DbHelper db = new DbHelper(getActivity());
		db.open();
		Cursor c = db.readUserTableData();
		int count = c.getCount();		
		for (int i = 0; i < count; i++) {
			c.moveToNext();
			String userName = c.getString(c
					.getColumnIndex(DbHelper.FIELD_U_USERNAME));
			String userType =  c.getString(c
					.getColumnIndex(DbHelper.FIELD_USERTYPE));
			String userId = c.getString(c
					.getColumnIndex(DbHelper.FIELD_USER_ID));
			row = new UserViewData();
			row.setUser(userName);
			row.setUserId(userId);
			if (userType.equals("2")) {
			    userType = getResources().getString(R.string.user_normal);
			} else if (userType.equals("1")) {
				userType = getResources().getString(R.string.user_manager);
			} else {
				userType = getResources().getString(R.string.user_admin);
			}
			row.setUserType(userType);
			row.setCheckBoxVisibility(false);
			row.setCheckedToEdit(false);
			row.setSpinnerVisibility(false);
			viewDataList.add(row);
		}
		db.close();
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.btnEdit:

			if (view == edit && edit.getText().equals(getResources().getString(R.string.edit))) {
				change.setVisibility(View.VISIBLE);
				for (UserViewData localObj : viewDataList) {
					localObj.setCheckBoxVisibility(true);
					adapter.notifyDataSetChanged();
				}
				edit.setText(R.string.cancel_txt);
				return ;
			}
			if (view == edit && edit.getText().equals(getResources().getString(R.string.cancel_txt))) {
				change.setVisibility(View.INVISIBLE);
				for (UserViewData localObj : viewDataList) {
					localObj.setCheckBoxVisibility(false);
					localObj.setCheckedToEdit(false);
					localObj.setEditTextEdit(false);
					localObj.setEditTextVisibility(true);
					localObj.setSpinnerVisibility(false);
					adapter.notifyDataSetChanged();
				}
				edit.setText(R.string.edit);
				return;
			}
		case R.id.btnChange:
			 change.setVisibility(View.GONE);
			 JSONObject jsonObj = null ;
			 JSONArray json = new JSONArray();
			 try {
				 int i=0;
				 for (UserViewData localObj : dataSendList) {
					 jsonObj = new JSONObject();
					 jsonObj.put("userid",localObj.getUserId());
					 jsonObj.put("username",localObj.getUser());
					 jsonObj.put("usertype", localObj.getUserType());
					 json.put(i,jsonObj);
					 i++;
				 }
				
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			 if (json.length() > 0) {
			     new ChangeRolesTask().execute(json.toString());
			 }
			 
			 return;
		}

	}
	
	public class ChangeRolesTask extends AsyncTask<String,Void,Boolean> {

		@Override
		protected Boolean doInBackground(String... params) {
			try {

				HttpClient http = new DefaultHttpClient();
				String server = AppVars.getServer();
				HttpPost post = new HttpPost(
						"http://"+server+"/gcminteraction/view/start.php?controlVar=14");
				JSONArray jsonArray = null;
				try {
					jsonArray = new JSONArray(params[0]);
					StringEntity se = new StringEntity(jsonArray.toString(),"UTF-8");
					se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
					post.setEntity(se);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				HttpResponse response = http.execute(post);
				String responseString = new BasicResponseHandler()
						.handleResponse(response); // Basic handler
				
				
				
				if(AppVars.isLogEnabled) {
					Log.v(AppVars.LOG_TAG,"Response String ="+responseString);
				}
				dataSendList.clear();
				return true;
			} catch (ClientProtocolException e) {
				e.printStackTrace();

			} catch (IOException e) {
				e.printStackTrace();
			}
			return false;
		}
		
	}
	
}
class CustomSpinnerAdapter extends ArrayAdapter<String> {
	
	String []dataArray = null;
	float fontSize;
	int dropDownRes;
	Context context;
	@Override
	public void setDropDownViewResource(int resource) {
		this.dropDownRes = resource;
	}
	public CustomSpinnerAdapter(Context context, int resource, int textViewResourceId, float fontSize) {
        super(context,textViewResourceId);
        this.context = context;
        this.dataArray = context.getResources().getStringArray(resource);
        this.fontSize = fontSize;
    }
    @Override
    public TextView getView(int position, View convertView, ViewGroup parent) {
        TextView v = (TextView) super.getView(position, convertView, parent);
        v.setText(dataArray[position]);
        return v;
    }

    @Override
    public TextView getDropDownView(int position, View convertView, ViewGroup parent) {
    	LayoutInflater li = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        TextView v = (TextView) li.inflate(dropDownRes,null);
        v.setText(dataArray[position]);
        return v;
    }
}
class EditorAdapter extends BaseAdapter {

	Context context;
	ArrayList<UserViewData> data;
	ArrayList<UserViewData> filteredData;
	
	EditText editText = null;
	TextView textView = null;
	CheckBox checkBox = null;
	Spinner spinner = null;

	public EditorAdapter(Context context,
			ArrayList<UserViewData> data,ArrayList<UserViewData> filteredData) {
		this.context = context;
		this.data = data;
		this.filteredData = filteredData;
	}

	@Override
	public int getCount() {
		int size = data.size();
		return size;
	}

	@Override
	public Object getItem(int pos) {
		return data.get(pos);
	}

	@Override
	public long getItemId(int pos) {
		return pos;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		final int finalPos = position;
		if (AppVars.isLogEnabled) {
		    Log.v(AppVars.LOG_TAG,"final postion"+finalPos);
		}
		View v = convertView;
		if (v == null) {
			v = LayoutInflater.from(context).inflate(
					R.layout.row_edit_string, null, false);
		}
		editText = (EditText) v
				.findViewById(R.id.editPropertyValue);
		textView = (TextView)v
				.findViewById(R.id.propertyName);
		checkBox = (CheckBox)v.findViewById(R.id.checkBox1);
		spinner = (Spinner)v.findViewById(R.id.spinner1);
		checkBox.setChecked(data.get(finalPos).isCheckedToEdit());
		int cbVisibility = data.get(finalPos).isCheckBoxVisibility() ? View.VISIBLE : View.GONE;
		checkBox.setVisibility(cbVisibility);
		textView.setText(data.get(finalPos).getUser());
		editText.setText(data.get(finalPos).getUserType());
		int edVisibility =  data.get(finalPos).isEditTextVisibility() ? View.VISIBLE : View.GONE;
		editText.setVisibility(edVisibility);
		editText.setEnabled(data.get(finalPos).isEditTextEdit());
		float fontSize = (int) editText.getTextSize();
		CustomSpinnerAdapter cs = new  CustomSpinnerAdapter(context,R.array.user_type_array,R.layout.spinneritem,fontSize);
		cs.addAll(Arrays.asList(context.getResources().getStringArray(
		        R.array.user_type_array)));
		cs.setDropDownViewResource(R.layout.spinneritem_dropdown);
		spinner.setAdapter(cs);
		String txt = editText.getText().toString();
		if (txt.equals(context.getResources().getString(R.string.user_normal))) {
			spinner.setSelection(1);   // for normal
		} else if (txt.equals(context.getResources().getString(R.string.user_manager))) {
			spinner.setSelection(2);    // for manager
		} else {
			spinner.setSelection(0); // for admin
		}
		int spVisibility = data.get(finalPos).isSpinnerVisibility() ? View.VISIBLE : View.GONE;
		spinner.setVisibility(spVisibility);
		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
			if (arg2 == 0) { 
				if (finalPos < filteredData.size())
				filteredData.get(finalPos).setUserType("3");
			} else if (arg2 == 1) {
				if (finalPos < filteredData.size())
				filteredData.get(finalPos).setUserType("2");
			} else {
				if (finalPos < filteredData.size())
				filteredData.get(finalPos).setUserType("1");
			}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		});

		
		checkBox.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (data.get(finalPos).isCheckedToEdit()) {
				    data.get(finalPos).setCheckedToEdit(false);
				    data.get(finalPos).setSpinnerVisibility(false);
				    data.get(finalPos).setEditTextVisibility(true);
				    filteredData.remove(data.get(finalPos));
				} else {
					data.get(finalPos).setCheckedToEdit(true);
					data.get(finalPos).setSpinnerVisibility(true);
				    data.get(finalPos).setEditTextVisibility(false);
				    filteredData.add(data.get(finalPos));
				}
				EditorAdapter.this.notifyDataSetChanged();
			}
		});
		
		return v;
	}

	static class ViewHolder {
		EditText editPropertyValue;
		TextView propertyName;
		Spinner spinner;
		CheckBox cb;
	}
}
